var Star = require("StarPrefab");
var Global = require("Global");
var GameData = require('GameData');
var Net = require('Net');
var curLevel = 1;
var targetScore = 1300;

cc.Class({
    extends: cc.Component,

    properties: {
        starPrefab: cc.Prefab,
        starGrid: cc.Node,
        scoreLabel: cc.Label,
        scorePreLabel: cc.Label,
        targetLabel: cc.Label,
        levelLabel: cc.Label,
        diamondNum: cc.Label,
        diamondTipPrefab: cc.Prefab,
        penTipNode: cc.Node,
        resultPrefab: cc.Prefab,
        leftLabel: cc.Label,
        curChargeLabel: cc.Label,
        curhammerLabel: cc.Label,
        freshLabel: cc.Label,
        penLabel: cc.Label,
        telChargePrefab: cc.Prefab,
        hammerNode: cc.Node,
        restartNode: cc.Node,
        rewardPrefab: cc.Prefab,
        goodPrefab: cc.Prefab,
        propPrefab: cc.Prefab,
        particlePreb: [cc.Prefab],
        hfNode: cc.Node,
        shareNode: cc.Node,
        topSkipSprite: [cc.Sprite]

    },

    onLoad: function () {
        if (JSON.stringify(GameData.curData) != "{}") {
            let data = GameData.curData;
            this.levelOver = data.levelOver;
            this.curStage = data.curStage;
            this.isFirstFail = data.isFirstFail;
            this.totalScore = data.score;
            targetScore = data.targetScore;
            this.continueLastGame(data.gridData);
            curLevel = data.level;
            this.levelLabel.string = curLevel.toString();
        }
        else {
            this.curStage = 0;
            this.StartGame();
            this.levelOver = false;
            this.isFirstFail = false;
            this.totalScore = 0;
        }

        Global.game = this;
        var self = this;

        this.freshUI();
        this.showIcon();
        this.touch = "normal";

        this.shareNode.getComponent("shareCanvas").showNextUI();
        this.starGrid.on(cc.Node.EventType.TOUCH_START, function (e) {
            var pos = self.starGrid.convertToNodeSpace(e.touch.getLocation());
            var x = parseInt(pos.x / (self.starGrid.width / 10));
            var y = parseInt(pos.y / (self.starGrid.height / 10));
            if (self.touch == "normal") {
                self.TouchStar(x, y);
            }
            else if (self.touch == "change") {
                self.changeColor(x, y);
            }
            else if (self.touch == "destroy") {
                self.destroyStar(x, y);
            }

        });


        if (Global.isShowCharge) {
            this.hfNode.active = true;
        }
    },

    showIcon: function () {
        var self = this;
        if (typeof wx != "undefined") {
            Net.requestUrl(Net.gameSkipUrl, function (data) {
                for (let i = 0; i < data.length; i++) {
                    self.scheduleOnce(function () {
                        cc.loader.load(data[i].pic, function (err, texture) {
                            let spriteFrame = new cc.SpriteFrame(texture);
                            self.topSkipSprite[i].spriteFrame = spriteFrame;
                            self.topSkipSprite[i].node.active = true;
                            self.topSkipSprite[i].node.on(cc.Node.EventType.TOUCH_START, function () {
                                wx.previewImage({
                                    urls: [data[i].skip]
                                })
                            })
                        })

                    })
                }
            })

        }
    },

    continueLastGame(data) {
        this.gameState = "ready";
        this.isShowProp = false
        this.InitStatus();
        this.InitLastGrid(data);
        this.UpdateTargetScore(targetScore);
    },

    InitLastGrid: function (data) {
        if (this.gridStarUi) {
            for (var x = 0; x < Global.gridSize; x++) {
                for (var y = 0; y < Global.gridSize; y++) {
                    if (this.gridStarUi[x][y]) {
                        this.gridStarUi[x][y].destroy();
                    }
                }
            }
        }
        var gridData = data;
        var gridStarUi = [];
        for (var i = 0; i < gridData.length; i++) {
            gridStarUi[i] = [];
            for (var j = 0; j < gridData[i].length; j++) {
                if (gridData[i][j] != 0) {
                    var star = cc.instantiate(this.starPrefab);
                    var starClass = star.getComponent("StarPrefab");
                    star.parent = this.starGrid;
                    starClass.SetGridPOS(i, j);
                    starClass.SetType(gridData[i][j]);
                    gridStarUi[i][j] = star;
                }

            }
        }

        this.gridData = gridData;
        this.gridStarUi = gridStarUi;
    },

    freshUI() {
        this.diamondNum.string = GameData.diamondNum;
        this.curChargeLabel.string = GameData.telCharge;
        this.curhammerLabel.string = GameData.hammerNum;
        this.freshLabel.string = GameData.freshItemNum;
        this.penLabel.string = GameData.penItemNum;

        if (Global.isOnline) {
            this.freshLabel.node.parent.active = true;
            this.penLabel.node.parent.active = true;
            this.curhammerLabel.node.parent.active = true;
            this.diamondNum.node.parent.active = true;
        }
    },

    onDiamondClick: function () {
        var self = this;
        var diamondNode = cc.instantiate(this.diamondTipPrefab);
        diamondNode.parent = this.node;
        diamondNode.getComponent("diamondTip").setCb(function () {
            self.freshUI();
        })
    },

    onPenBtnClick: function () {
        if (GameData.penItemNum > 0) {
            this.penTipNode.active = true;
            this.touch = "change";
        }
        else {
            if (GameData.checkDiamondEnough(50)) {
                this.penTipNode.active = true;
                this.touch = "change";
            }
            else {
                var self = this;
                var diamondNode = cc.instantiate(this.diamondTipPrefab);
                diamondNode.parent = this.node;
                diamondNode.getComponent("diamondTip").setCb(function () {
                    self.freshUI();
                })
            }
        }

    },

    onPenItemClick: function (sender, event) {
        if (this.chooseStar.length == 0) {
            return;
        }
        var x = this.chooseStar[0];
        var y = this.chooseStar[1];
        if (this.chooseStar.length == 0 || this.gridData[x][y] == parseInt(event)) {
            return;
        }
        this.gridData[x][y] = parseInt(event);
        this.gridStarUi[x][y].getComponent("StarPrefab").SetType(parseInt(event));
        this.touch = "normal";
        for (let j = 0; j < Global.gridSize; j++) {
            for (let k = 0; k < Global.gridSize; k++) {
                if (this.gridStarUi[j][k] != null) {
                    if (this.gridStarUi[j][k].active == false) {
                        this.gridStarUi[j][k].destroy();
                    }
                    else {
                        this.gridStarUi[j][k].getChildByName('frame').active = false;
                    }
                }
            }
        }
        this.penTipNode.active = false;
        if (GameData.penItemNum > 0) {
            GameData.penItemNum--;
            GameData.savePenNum();
        }
        else {
            GameData.costDimaond(50);
        }

        this.chooseStar = [];
        this.freshUI();
    },

    onClosePenClick: function () {
        this.penTipNode.active = false;
        this.touch = "normal";
        this.chooseStar = [];
        for (let j = 0; j < Global.gridSize; j++) {
            for (let k = 0; k < Global.gridSize; k++) {
                if (this.gridStarUi[j][k] != null) {
                    if (this.gridStarUi[j][k].active == false) {
                        this.gridStarUi[j][k].destroy();
                    }
                    else {
                        this.gridStarUi[j][k].getChildByName('frame').active = false;
                    }
                }
            }
        }
    },

    onCloseHammer: function () {
        this.hammerNode.active = false;
        this.touch = 'normal';
    },

    onFreshClick: function () {
        if (GameData.freshItemNum > 0) {
            GameData.freshItemNum--;
            GameData.saveFreshNum();
            if (this.gameState == "ready") {
                this.StartGame();
            }
            else {
                this.freshStar();
            }

            this.freshUI();
        }
        else {
            if (GameData.checkDiamondEnough(50)) {
                GameData.costDimaond(50);
                if (this.gameState == "ready") {
                    this.StartGame();
                }
                else {
                    this.freshStar();
                }
                this.freshUI();
            }
            else {
                var self = this;
                var diamondNode = cc.instantiate(this.diamondTipPrefab);
                diamondNode.parent = this.node;
                diamondNode.getComponent("diamondTip").setCb(function () {
                    self.freshUI();
                })
            }
        }
    },


    onHammerClick: function () {
        if (this.hammerNode.active == false) {

            if (GameData.hammerNum > 0 || GameData.checkDiamondEnough(50)) {
                this.touch = "destroy";
                this.hammerNode.active = true;
            }
            else {
                var self = this;
                var diamondNode = cc.instantiate(this.diamondTipPrefab);
                diamondNode.parent = this.node;
                diamondNode.getComponent("diamondTip").setCb(function () {
                    self.freshUI();
                })
            }
        }
        else {
            this.onCloseHammer();
        }

    },

    freshStar: function () {
        for (var i = 0; i < Global.gridSize; i++) {
            for (var j = 0; j < Global.gridSize; j++) {
                if (this.gridData[i][j] != 0) {
                    var rnd = parseInt(Math.random() * 5 + 1);
                    this.gridData[i][j] = rnd;
                    this.gridStarUi[i][j].getComponent("StarPrefab").SetType(rnd);
                }
            }
        }
    },

    StartGame: function () {
        this.gameState = "ready";
        this.isShowProp = false;
        this.InitStatus();
        this.InitGrid();
        this.UpdateTargetScore(targetScore);
    },


    InitStatus: function () {
        this.stVar = {};
        this.stVar.selected = false;
        this.chooseStar = [];
    },

    InitGrid: function () {
        if (this.gridStarUi) {
            for (var x = 0; x < Global.gridSize; x++) {
                for (var y = 0; y < Global.gridSize; y++) {
                    if (this.gridStarUi[x][y]) {
                        this.gridStarUi[x][y].destroy();
                    }
                }
            }
        }
        var gridData = [];
        var gridStarUi = [];
        for (var i = 0; i < Global.gridSize; i++) {
            gridData[i] = [];
            gridStarUi[i] = [];
            for (var j = 0; j < Global.gridSize; j++) {
                var star = cc.instantiate(this.starPrefab);
                var starClass = star.getComponent("StarPrefab");
                star.parent = this.starGrid;
                starClass.SetGridPOS(i, j);
                var rnd = parseInt(Math.random() * 5 + 1);
                starClass.SetType(rnd);
                gridData[i][j] = rnd;
                gridStarUi[i][j] = star;
            }
        }

        this.gridData = gridData;
        this.gridStarUi = gridStarUi;
    },

    UpdateTargetScore: function (score) {
        score ? score : 0;
        this.targetLabel.string = score.toString();
    },

    TouchStar: function (x, y) {
        Global.playAudio.click();
        if (this.gridData[x][y] == 0) { return; }

        this.stVar.connectStars = [[x, y]];
        this.CheckLinkStars(x, y);

        if (this.stVar.connectStars) {
            if (this.stVar.connectStars.length >= 2) {
                var starNode = cc.instantiate(this.particlePreb[this.gridData[x][y]]);
                starNode.setPosition(this.gridStarUi[x][y].position);
                starNode.parent = this.node;
                this.gameState = "start";
                this.scorePreLabel.string = Global.GetScores(this.stVar.connectStars.length);
                this.scorePreLabel.node.stopAllActions();
                this.scorePreLabel.node.setPosition(this.gridStarUi[x][y].position);
                this.scorePreLabel.node.opacity = 255;
                this.scorePreLabel.fontSize = 32;
                this.scorePreLabel.node.active = true;
                this.CleanStars(x, y);
            }

            if (this.stVar.connectStars.length >= 8) {
                var goodNode = cc.instantiate(this.goodPrefab);
                goodNode.parent = this.node;
                goodNode.setPosition(this.gridStarUi[x][y].position);
                goodNode.getComponent("goodPrefab").showUI(this.stVar.connectStars.length);
            }
        }


    },

    changeColor: function (x, y) {
        if (this.gridData[x][y] == 0) { return; }

        for (let j = 0; j < Global.gridSize; j++) {
            for (let k = 0; k < Global.gridSize; k++) {
                if (this.gridStarUi[j][k] != null) {
                    if (this.gridStarUi[j][k].active == false) {
                        this.gridStarUi[j][k].destroy();
                    }
                    else {
                        this.gridStarUi[j][k].getChildByName('frame').active = false;
                    }
                }
            }
        }
        this.gridStarUi[x][y].getChildByName("frame").active = true;
        this.chooseStar = [];
        this.chooseStar = [x, y];
    },

    destroyStar(x, y) {

        var self = this;
        var callFunc = function () {
            self.onCloseHammer();
            self.scorePreLabel.string = Global.GetScores(1);
            self.scorePreLabel.node.stopAllActions();
            self.scorePreLabel.node.setPosition(self.gridStarUi[x][y].position);
            self.scorePreLabel.node.opacity = 255;
            self.scorePreLabel.fontSize = 32;
            self.scorePreLabel.node.active = true;

            self.scorePreLabel.fontSize = 64;
            self.scorePreLabel.node.runAction(cc.sequence(
                cc.moveBy(0.2, cc.v2(0, 20)),
                cc.delayTime(0.1),
                cc.spawn(cc.moveBy(0.2, cc.v2(0, 10)), cc.fadeOut(0.2))
            ));
            self.gridStarUi[x][y].destroy();
            self.gridData[x][y] = 0;
            self.checkGameUI();
            self.freshUI();
        }
        if (this.gridData[x][y] == 0) { return; }
        if (GameData.hammerNum > 0) {
            GameData.hammerNum--;
            GameData.saveHammerNum();
            callFunc();
            this.freshUI();
            this.touch = "normal"

        }
        else {
            if (GameData.checkDiamondEnough(50)) {
                GameData.costDimaond(50);
                this.touch = "normal"
                callFunc();
                this.freshUI();
            }
            else {
                var self = this;
                var diamondNode = cc.instantiate(this.diamondTipPrefab);
                this.onCloseHammer();
                diamondNode.parent = this.node;
                diamondNode.getComponent("diamondTip").setCb(function () {
                    self.freshUI();
                    this.touch = "normal"
                })
            }
        }



    },

    CheckLinkStars: function (x, y) {
        var starType = this.gridData[x][y];
        var scanStar = [[x + 1, y], [x - 1, y], [x, y - 1], [x, y + 1]];
        for (var i = scanStar.length - 1; i >= 0; i--) {
            scanStar[i]
            var scanX = scanStar[i][0];
            var scanY = scanStar[i][1];
            if (this.InGrid(scanX, scanY)
                && this.gridData[scanX][scanY] == starType
                && (!this.ConnectContain(scanX, scanY))
            ) {
                this.stVar.connectStars[this.stVar.connectStars.length] = [scanX, scanY];
                this.CheckLinkStars(scanX, scanY);
            }
        }
    },

    InGrid: function (x, y) {
        return x >= 0 && x < Global.gridSize && y >= 0 && y < Global.gridSize
    },

    ConnectContain: function (x, y) {
        for (var i = this.stVar.connectStars.length - 1; i >= 0; i--) {
            var star = this.stVar.connectStars[i];
            if (star[0] == x && star[1] == y) {
                return true;
            }
        }
        return false;
    },

    CleanStars: function () {
        this.scorePreLabel.fontSize = 64;
        this.scorePreLabel.node.runAction(cc.sequence(
            cc.moveBy(0.2, cc.v2(0, 20)),
            cc.delayTime(0.1),
            cc.spawn(cc.moveBy(0.2, cc.v2(0, 10)), cc.fadeOut(0.2))
        ));
        var data = {
            "level": curLevel,
            "score": this.totalScore,
            "gridData": this.gridData,
            "curStage": this.curStage,
            "levelOver": this.levelOver,
            "isFirstFail": this.isFirstFail,
            "targetScore": targetScore,
        };

        GameData.saveCurData(data);

        this.totalScore += parseInt(this.scorePreLabel.string);

        this.checkGift();
        this.scoreLabel.string = this.totalScore;



        if (this.totalScore > targetScore && this.levelOver == false) {
            this.levelOver = true;
            var resultNode = cc.instantiate(this.resultPrefab);

            resultNode.parent = this.node;
            resultNode.getComponent('resultUI').init(true)
        }

        if (this.totalScore > GameData.maxScore) {
            GameData.saveMaxScore(this.totalScore);
            this.shareNode.getComponent("shareCanvas").subMaxScore(this.totalScore);
            this.shareNode.getComponent("shareCanvas").showNextUI();
            this.freshUI();
        }

        this.ClearStars();
        var leftStar = this.CountStars();
        if (leftStar >= 20 && leftStar <= 30 && Global.isOnline) {
            this.showPropUI();
        }
        this.checkGameUI();
    },

    showPropUI: function () {
        if (!Global.game.isGetGift && this.isShowProp == false) {
            this.isShowProp = true;
            var propUI = cc.instantiate(this.propPrefab);
            propUI.parent = this.node;
        }
    },

    checkGift: function () {
        var stage = Math.floor(this.totalScore / 920)
        if (stage > this.curStage) {
            this.showrewardUI();
            this.curStage++;
        }
    },

    showrewardUI: function () {
        if(!Global.isOnline){
            return;
        }
        this.isGetGift = true;
        var rewardNode = cc.instantiate(this.rewardPrefab);
        rewardNode.parent = this.node;
        var self = this;
        rewardNode.getComponent("rewardTip").setCb(function () {
            self.freshUI();
        })
    },

    checkGameUI() {
        this.StarFallDown();
        this.StarsMoveLeft();
        if (this.CheckGameOver()) {
            var data = {};
            GameData.saveCurData(data);

            this.levelOver = false;
            if (targetScore < this.totalScore) {
                var leftStar = this.CountStars();
                if (leftStar <= 9) {
                    var self = this;
                    this.leftLabel.node.active = true;
                    this.leftLabel.string = "剩余" + leftStar + "个,加" + Global.extraScore[leftStar] + "分";
                    this.leftLabel.node.zIndex = 9999;
                    this.leftLabel.node.runAction(cc.sequence(cc.moveBy(0.3, cc.v2(0, 20)), cc.delayTime(1), cc.callFunc(function () {
                        self.leftLabel.node.active = false;
                        self.leftLabel.node.x = 0;
                        self.leftLabel.node.y = 0;
                        self.totalScore += Global.extraScore[leftStar];
                        self.checkGift();
                        self.scoreLabel.string = self.totalScore;
                        if (self.totalScore > GameData.maxScore) {
                            GameData.saveMaxScore(self.totalScore);
                            self.freshUI();
                        }
                        self.isSuccess = true;
                        self.playSuccessAinm();

                    })));
                }
                else {
                    this.isSuccess = true;
                    this.playSuccessAinm();
                }


            } else {
                //未通关
                this.isSuccess = false;
                if (this.isFirstFail == true) {
                    this.restartNode.active = true;
                }
                else {
                    var resultNode = cc.instantiate(this.resultPrefab);
                    resultNode.parent = this.node;
                    resultNode.getComponent('resultUI').init(false);
                    this.isFirstFail = true;
                }
            }
        }
    },

    playSuccessAinm: function () {
        var self = this;
        var temp = 0;
        for (let i = 0; i < this.gridData.length; i++) {
            for (let j = 0; j < this.gridData[i].length; j++) {
                if (this.gridData[i][j] != 0) {
                    temp++;
                    this.scheduleOnce(function () {
                        var starNode = cc.instantiate(self.particlePreb[self.gridData[i][j]]);
                        starNode.setPosition(self.gridStarUi[i][j].position);
                        starNode.parent = self.node;
                        self.gridStarUi[i][j].active = false;
                        Global.playAudio.click();
                    }, temp * 0.1)
                }
                if (i == 9 && j == 9) {
                    this.scheduleOnce(function () {
                        self.Continue();
                    }, temp * 0.1)
                }
            }
        }
    },

    Continue: function (cb) {
        if (this.isSuccess == false) {
            var self = this;

            if (!Global.canShare) {
                this.Restart();
                if (cb) {
                    cb();
                }
            }
            else {
                var completecallback = function () {
                    self.continueGame();
                    if (cb) {
                        cb();
                    }
                }
                Global.getByAD(completecallback);
            }

        } else {
            curLevel++;
            targetScore = Global.GetTargetScore(curLevel);
            this.UpdateTargetScore(targetScore);
            this.levelLabel.string = curLevel.toString();
            this.StartGame();
        }
    },

    onCloseClick: function () {
        if (this.isSuccess == false) {
            this.Restart();
        }
        else {
            curLevel++;
            targetScore = Global.GetTargetScore(curLevel);
            this.UpdateTargetScore(targetScore);
            this.levelLabel.string = curLevel.toString();
            this.StartGame();
        }
    },

    Restart: function () {
        if (this.restartNode.active == true) {
            this.restartNode.active = false;
        }
        this.isFirstFail = false;
        curLevel = 1;
        targetScore = 1300;
        this.totalScore = 0;
        this.curStage = 0;
        this.UpdateTargetScore(targetScore);
        this.scoreLabel.string = "0";
        this.levelLabel.string = curLevel.toString();
        this.StartGame();
    },

    continueGame() {
        this.StartGame();
    },


    ClearStars: function () {


        for (var i = this.stVar.connectStars.length - 1; i >= 0; i--) {
            var star = this.stVar.connectStars[i];
            this.gridData[star[0]][star[1]] = 0;
            this.gridStarUi[star[0]][star[1]].destroy();
        }
    },

    StarFallDown: function () {
        for (var x = 0; x < Global.gridSize; x++) {
            var fallDistance = 0;
            for (var y = 0; y < Global.gridSize; y++) {
                if (this.gridData[x][y] == 0) {
                    fallDistance++;
                }
                if (fallDistance > 0 && this.gridData[x][y] > 0) {
                    this.gridData[x][y - fallDistance] = this.gridData[x][y];
                    this.gridData[x][y] = 0;
                    this.gridStarUi[x][y].getComponent(Star).MoveTo(x, y - fallDistance, 0);
                    this.gridStarUi[x][y - fallDistance] = this.gridStarUi[x][y];
                    this.gridStarUi[x][y] = null;
                }
            }
        }
    },


    StarsMoveLeft: function () {
        var fallLeftDistance = 0;
        for (var x = 0; x < Global.gridSize; x++) {
            if (this.gridData[x][0] == 0) {
                fallLeftDistance++;
            }
            if (this.gridData[x][0] != 0 && fallLeftDistance != 0) {
                for (var y = 0; y < Global.gridSize; y++) {
                    if (this.gridData[x][y] > 0) {
                        this.gridData[x - fallLeftDistance][y] = this.gridData[x][y];
                        this.gridData[x][y] = 0;
                        this.gridStarUi[x][y].getComponent(Star).MoveTo(x - fallLeftDistance, y, 0.1);
                        this.gridStarUi[x - fallLeftDistance][y] = this.gridStarUi[x][y];
                        this.gridStarUi[x][y] = null;
                    } else {
                        break;
                    }
                }
            }
        }
    },

    CheckGameOver: function () {
        for (var x = 0; x < Global.gridSize; x++) {
            for (var y = 0; y < Global.gridSize; y++) {
                var starType = this.gridData[x][y];
                if (starType == 0) {
                    break;
                }
                var scanStar = [[x + 1, y], [x - 1, y], [x, y - 1], [x, y + 1]];
                for (var i = 0; i < scanStar.length; i++) {
                    var tmpX = scanStar[i][0];
                    var tmpY = scanStar[i][1];
                    if (this.InGrid(tmpX, tmpY) && this.gridData[tmpX][tmpY] == starType) {
                        return false
                    }
                }
            }
        }
        return true
    },

    CountStars: function () {
        var count = 0;
        for (var x = 0; x < Global.gridSize; x++) {
            for (var y = 0; y < Global.gridSize; y++) {
                var starType = this.gridData[x][y];
                if (starType > 0) {
                    count++;
                }
            }
        }
        return count;
    },


    onGetTelChargeClick: function () {
        var telChargeNode = cc.instantiate(this.telChargePrefab);
        telChargeNode.parent = this.node;
        var self = this;
        telChargeNode.getComponent("telChargeUI").setCb(function () {
            self.freshUI();
        })
    },

    onReturnClick: function () {
        cc.director.loadScene('WelcomeScene');
    }
});
